﻿using AppManager.BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json.Linq;

namespace PushManager.Web
{
    /// <summary>
    /// 這個項目兩個功能
    /// 1.記錄哪些設備連接了
    /// 2.向連接的設備發送消息
    /// </summary>
    public class MsgHub : BaseDbHub
    {
        /// <summary>
        /// console中调用该方法
        /// <param name="message"></param>
        /// <param name="devices"></param>
        /// </summary>
        /// <param name="messageIds"></param>
        public void Send(string message, string[] devices)
        {
            //這裡通過對比connect表中console的connectionid和context.connectionid對比然後判斷
            var connect = ConnectBLL.GetList(s => s.IsAdmin).FirstOrDefault();
            if (connect == null) return;
            if (connect.ConnectionId != Context.ConnectionId) return;

            //传入需要发送的设备，然后获取clientid
            var list = ConnectBLL.GetList(s => devices.Contains(s.DeviceStr) && s.IsConnected && !s.IsAdmin);

            var connectionIds = list.Select(s => s.ConnectionId).ToList();
            var client = Clients.Clients(connectionIds);

            JObject jObj = JObject.Parse(message);                        
            client.Invoke("msgReceive", jObj);
        }

        /// <summary>
        /// client回調該方法，更新發送狀態
        /// </summary>
        /// <param name="messageId"></param>
        /// <param name="deviceStr"></param>
        public void ClientNotify(string para)
        {
            if (!string.IsNullOrEmpty(para))
            {
                //这边有一个问题，就是Signalr只能在成功的时候回调这个东西，除非我有一个超时的东西来判断失败
                var arr = para.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                if (arr.Length >= 2)
                {
                    int messageId = 0;
                    if (int.TryParse(arr[0], out messageId))
                    {
                        var deviceStr = arr[1];
                        MessageDeviceBLL.UpdateRemoteServer(true, messageId, deviceStr);
                    }
                }
            }
        }
    }
}